package com.originit.product.server.service.impl

import com.originit.product.common.input.CartInput
import com.originit.product.common.output.ProductOutput
import com.originit.product.server.dao.ProductCategoryRepository
import com.originit.product.server.dao.ProductInfoRepository
import com.originit.product.server.entity.ProductInfo
import com.originit.product.server.enums.ProductEnum
import com.originit.product.server.enums.ResultEnum
import com.originit.product.server.exception.ProductException
import com.originit.product.server.service.ProductService
import org.slf4j.LoggerFactory
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import kotlin.Exception

@Service
class ProductServiceImpl : ProductService {
    
    val log = LoggerFactory.getLogger(ProductServiceImpl::class.java)

    @Autowired
    lateinit var productInfoRepository: ProductInfoRepository

    @Autowired
    lateinit var productCategoryRepository: ProductCategoryRepository

    override fun findUpAll(): List<ProductInfo> {
        return productInfoRepository.findByProductStatus(ProductEnum.UP.code)
    }

    override fun findForOrderByIds(ids: List<String>): List<ProductOutput> {
        return productInfoRepository.findAllById(ids).map {
            val output = ProductOutput()
            BeanUtils.copyProperties(it, output)
            output
        }
    }

    @Transactional(rollbackFor = [Exception::class])
    override fun minusStockByIds(productStockList: List<CartInput>) {
        // 循环减库存，效率相当的低
        productStockList.forEach {cart ->
            val optionalProduct = productInfoRepository.findByProductId(cart.productId!!)
            if (optionalProduct.isPresent.not()) {
                log.error("【减库存】商品不存在,id={}",cart.productId)
                throw ProductException(ResultEnum.PRODUCT_NOT_EXIST)
            }
            val product = optionalProduct.get()
            if (product.productStock != null && product.productStock!! < cart.productQuantity!!) {
                log.error("【减库存】商品库存不足,id={},库存={},需求={}",cart.productId,product.productStock,cart.productQuantity)
                throw ProductException(ResultEnum.GOOD_STOCK_NOT_ENOUGH)
            }
            product.productStock = product.productStock!!.minus(cart.productQuantity!!)
            productInfoRepository.save(product)
        }
    }
}